#include "cdgclock.h"

#include <math.h>
#include <iostream>

using namespace std;

cdgclock::cdgclock()
{
    // Pre-calculate sin & cos
    for (unsigned int i=0; i<361; ++i) {
        sinval.push_back(sin(i*M_PI/180));
        cosval.push_back(cos(i*M_PI/180));
    }
    m_current = 0;
    m_maxtime = 0;
}

void cdgclock::init(int width, int height, unsigned int maxtime)
{
    m_width = width;
    m_height = height;
    m_maxtime = maxtime; 
    m_current = 0;
    cout << "cdgclock:init w:" << m_width << " h:" << m_height << " maxtime: " << m_maxtime << endl;
}

void cdgclock::setTime(unsigned int currentTime)
{
    m_current = currentTime;
    //cout << "setTime: " << m_current << endl; 
}

void cdgclock::paintGL(void)
{
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glDisable(GL_TEXTURE_2D);
    glEnable(GL_POLYGON_SMOOTH);
    glEnable(GL_LINE_SMOOTH);

    //cerr << "m_width: " << m_width << " m_height: " << m_height << endl;
    glOrtho(0, m_width, m_height, 0, -9, 9);
    
    int radius = 30;
        
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

    // Draw outer circle
    //cerr << "Draw outer circle" << endl;
    glBegin(GL_LINE_LOOP);
    {
        for (unsigned int i=0; i<361; ++i) {
            glVertex2f(m_width-80.0f + sinval.at(i) * radius, m_height-80.0f + cosval.at(i) * radius);
        }
    }
    glEnd(); 

    //cerr << "Draw inner fill" << endl;
    // Draw inner fill
    glBegin(GL_TRIANGLE_FAN);
    {

        // Circle centre
        glVertex2f(m_width-80.0f, m_height-80.0f);
        
        for (unsigned int i=0; i<(m_current*360/m_maxtime); ++i) {
            //cerr << i << " max:" << m_current*360/m_maxtime << " cur:" << m_current << " max:"<<m_maxtime << endl;
            glVertex2f(m_width-80.0f + sinval.at(i) * radius, m_height-80.0f + -1*cosval.at(i) * radius);
        }
    }
    glEnd(); 

    glDisable(GL_LINE_SMOOTH);
    glDisable(GL_POLYGON_SMOOTH);
    glEnable(GL_TEXTURE_2D);

}

